"""
通用视频搜索管理器
支持多个平台的视频搜索和信息提取
"""

import asyncio
import sys
import os
import json

# Add the project root directory to the Python path
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from src.video_generator.douyin_video_search import DouyinVideoSearcher
from src.video_generator.kuaishou_video_search import KuaishouVideoSearcher
from src.video_generator.xiaohongshu_video_search import XiaohongshuVideoSearcher
from src.video_generator.bilibili_video_search import BilibiliVideoSearcher


class VideoSearchManager:
    """
    视频搜索管理器，支持多个平台的视频搜索
    """
    
    PLATFORMS = {
        'douyin': DouyinVideoSearcher,
        'kuaishou': KuaishouVideoSearcher,
        'xiaohongshu': XiaohongshuVideoSearcher,
        'bilibili': BilibiliVideoSearcher
    }
    
    def __init__(self):
        """
        初始化视频搜索管理器
        """
        self.searchers = {}
    
    async def search_videos(self, platform, keyword, max_count=50):
        """
        在指定平台搜索视频
        
        Args:
            platform (str): 平台名称 ('douyin', 'kuaishou', 'wechat', 'xiaohongshu', 'bilibili')
            keyword (str): 搜索关键词
            max_count (int): 最大获取视频数量
            
        Returns:
            list: 视频信息列表
        """
        if platform not in self.PLATFORMS:
            raise ValueError(f"不支持的平台: {platform}，支持的平台有: {list(self.PLATFORMS.keys())}")
        
        # 创建对应平台的搜索器实例
        searcher_class = self.PLATFORMS[platform]
        searcher = searcher_class()
        
        try:
            # 启动浏览器
            await searcher.start_browser(headless=False)
            
            # 搜索视频
            videos = await searcher.search_videos(keyword, max_count)
            
            # 为每个视频添加平台信息
            for video in videos:
                video['platform'] = platform
            
            return videos
        finally:
            # 关闭浏览器
            await searcher.close()
    
    async def manual_login(self, platform):
        """
        手动登录指定平台，用于处理需要人工验证的登录场景
        
        Args:
            platform (str): 平台名称 ('douyin', 'kuaishou', 'wechat', 'xiaohongshu', 'bilibili')
        """
        if platform not in self.PLATFORMS:
            raise ValueError(f"不支持的平台: {platform}，支持的平台有: {list(self.PLATFORMS.keys())}")
        
        # 创建对应平台的搜索器实例
        searcher_class = self.PLATFORMS[platform]
        searcher = searcher_class()
        
        try:
            # 启动浏览器并保持打开状态
            await searcher.start_browser(headless=False)
            print(f"已启动{platform}浏览器，请手动完成登录操作...")
            print("登录完成后，请按Ctrl+C关闭浏览器")
            
            # 保持浏览器打开，直到用户手动关闭
            while True:
                await asyncio.sleep(1)
        except KeyboardInterrupt:
            print(f"\n{platform}手动登录会话结束")
        finally:
            # 关闭浏览器
            await searcher.close()
    
    async def search_all_platforms(self, keyword, max_count_per_platform=50):
        """
        在所有支持的平台搜索视频
        
        Args:
            keyword (str): 搜索关键词
            max_count_per_platform (int): 每个平台最大获取视频数量
            
        Returns:
            dict: 各平台视频信息字典
        """
        results = {}
        
        for platform in self.PLATFORMS:
            try:
                print(f"正在搜索 {platform} 平台的视频...")
                videos = await self.search_videos(platform, keyword, max_count_per_platform)
                results[platform] = videos
                print(f"在 {platform} 平台找到 {len(videos)} 个视频")
            except Exception as e:
                print(f"搜索 {platform} 平台视频时发生错误: {e}")
                results[platform] = []
        
        return results


async def main():
    """
    主函数，处理命令行参数并执行搜索
    """
    if len(sys.argv) < 2:
        print("使用方法:")
        print("  python video_search_manager.py <关键词> [数量]")
        print("  python video_search_manager.py <平台> <关键词> [数量]")
        print("  python video_search_manager.py login <平台>  # 手动登录指定平台")
        print("\n示例:")
        print("  python video_search_manager.py 足球高清 50")
        print("  python video_search_manager.py douyin 足球高清 30")
        print("  python video_search_manager.py kuaishou 美食教程 20")
        print("  python video_search_manager.py login douyin  # 手动登录抖音")
        return
    
    # 解析命令行参数
    if len(sys.argv) == 2:
        # 只提供关键词，默认在所有平台搜索
        keyword = sys.argv[1]
        max_count = 50
        platform = None
    elif len(sys.argv) == 3:
        # 提供平台和关键词，或关键词和数量，或login命令
        arg1, arg2 = sys.argv[1], sys.argv[2]
        if arg1 == 'login':
            # 手动登录模式
            manager = VideoSearchManager()
            await manager.manual_login(arg2)
            return
        elif arg1 in VideoSearchManager.PLATFORMS:
            platform = arg1
            keyword = arg2
            max_count = 50
        else:
            platform = None
            keyword = arg1
            max_count = int(arg2) if arg2.isdigit() else 50
    else:
        # 提供平台、关键词和数量
        platform = sys.argv[1] if sys.argv[1] in VideoSearchManager.PLATFORMS else None
        keyword = sys.argv[2] if platform else sys.argv[1]
        max_count_index = 3 if platform else 2
        max_count = int(sys.argv[max_count_index]) if len(sys.argv) > max_count_index and sys.argv[max_count_index].isdigit() else 50
    
    print(f"正在搜索关键词: '{keyword}'")
    if platform:
        print(f"搜索平台: {platform}")
    else:
        print("搜索平台: 所有平台")
    print(f"获取数量: {max_count}")
    
    # 创建搜索管理器实例
    manager = VideoSearchManager()
    
    try:
        if platform:
            # 在指定平台搜索
            videos = await manager.search_videos(platform, keyword, max_count)
            # 输出JSON格式结果
            print(json.dumps(videos, ensure_ascii=False, indent=2))
        else:
            # 在所有平台搜索
            results = await manager.search_all_platforms(keyword, max_count)
            # 输出JSON格式结果
            print(json.dumps(results, ensure_ascii=False, indent=2))
            
    except Exception as e:
        print(f"搜索过程中发生错误: {e}")


if __name__ == "__main__":
    asyncio.run(main())